import axios from 'axios'
import store from '@/store'
import { Notification, detailBox, Message } from 'element-ui'
import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // 当跨域请求时发送cookie
  timeout: 10000 // 请求超时时间
})

// request 拦截器
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // 让每个请求携带令牌
      // ['X-Token']是一个自定义头键
      // 请根据实际情况修改
      config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * 如果您想获得http信息，例如头信息或状态信息
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    const code = response.status
    // if the custom code is not 200, it is judged as an error.
    if (code < 200 || code > 300) {
      Notification.error({
        title: '错误',
        message: response.data
      })
      // 508:非法token;512:其他客户登录;514:token过期;
      if (code === 508 || code === 512 || code === 514) {
        // 重新登录
        detailBox.confirm(
          '您已经注销，您可以取消以停留在此页面，或再次登录',
          'Confirm logout',
          {
            confirmButtonText: 'Re-Login',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    if (error.response.data.data != null) {
      Notification.error({
        title: '错误',
        message: error.response.data.data,
        duration: 2500
      })
      console.log(error.response)
    } else {
      Message.error(error.response.data.msg)
    }
    return Promise.reject(error)
  }
)

export default service
